<?php


namespace app\unify\validate;


use think\Validate;
use app\unify\model\Config as ConfigModel;

class Config extends Validate
{


    const UPDATE = 'Update';
    const SAVE = "Save";

    const SET_VALUES = 'SetValues';
    const UPDATE_FIELD = "UpdateField";
    const DELETE = 'Delete';


    protected $rule = [
        'groupId|配置分组' => 'require',
        'name|配置标识' => 'require',
        'title|配置标题' => 'require',
        'type|配置类型' => 'require',
        'options|配置选项' => 'requireIf:type,' . ConfigModel::TYPE_SELECT,
        'tips|配置提示' => 'length:0,255',
        'status|配置状态' => "require|in:" . ConfigModel::STATUS_ENABLE . ',' . ConfigModel::STATUS_DISABLE,
        'default|默认值' => 'length:0,50',
        'serial|排序号' => 'require|number',
        'id|编号' => 'require|integer',
        'ids|编号集合' => 'require|array',
        'field|字段' => 'require|in:status,serial',
        'value|值' => "require",
        'data' => 'require|checkValidData'
    ];

    protected $scene = [
        self::SAVE => ['group_id', 'name', 'title', 'type', 'options', 'tips', 'status', 'default'],
        self::UPDATE => ['id', 'group_id', 'name', 'title', 'type', 'options', 'tips', 'status', 'default'],
        self::UPDATE_FIELD => ['ids', 'field', 'value'],
        self::DELETE => ['ids'],
        self::SET_VALUES => ['data']
    ];

    public function checkValidData($data)
    {
        if (!is_array($data)) {
            return '数据格式不正确';
        }
        foreach ($data as $item) {
            $result = \think\facade\Validate::rule([
                'title' => 'require',
                'id' => 'require',
                'type' => 'require'
            ])->check($item);
            if ($result !== true) {
                return ($item['title'] ?? '') . '格式不正确';
            }
        }

        return true;
    }
}